class TwitterController < ApplicationController
  before_filter :login_required, :except => 'index'
  layout 'master'
  #Retreive the friend activities
  def slow_cloud
    id = params[:id] || current_user.twitter_id
    @profiles = User.friend_profiles(id)
    if @profiles.nil? or @profiles.size == 0
      current_user.refresh
      @profiles = User.friend_profiles(id)
    end
    @user = User.find_by_twitter_id(id) || current_user
  end
  
    # I think for Robert's test the users not already in the db caused the following error:
    #Processing TwitterController#user_image (for 128.171.10.89 at 2009-05-27 16:01:20) [GET]
    #  Parameters: {"id"=>"9490962", "friend_id"=>"9488282"}

    #ActionView::TemplateError (undefined method `[]' for nil:NilClass) on line #1 of app/views/twitter/_user_image.html.erb:
    #1: <% size = @profile[:score].to_f + 0.2%><%=link_to image_tag(@profile[:image], :border=>0, :title => "#{@profile[:screen_name]} data last pulled from twitter #{time_since(@profile[:updated_at])}", :height=>size*96, :width=>size*96, :alt => @profile[:name]), "http://www.twitter.com/#{@profile[:screen_name]}" %>

    #    app/views/twitter/_user_image.html.erb:1
    #    app/views/twitter/_load.rjs:1:in `__instance_exec0'
    #    app/views/twitter/_load.rjs:1:in `_run_rjs_app47views47twitter47_load46rjs_locals_load_object'
    #    app/controllers/twitter_controller.rb:24:in `user_image'
    
    # seems like that would be caused by profile being nil - should re-search for profile, but would have thought it would be guaranteed to be there
    # because of call to user.friends in cloud - should investigate - think it might fail to be there if there are no statuses yet 
    
    # Robert was also saying I should have countdown, e.g. 3/45 friends, 7/45 friends as we upload them ...
  
  def user_image
    id = params[:id] || current_user.twitter_id
    friend_id = params[:friend_id]
    refresh = params[:refresh]
    @profile = User.friend_profile(id,friend_id)
    if @profile.nil? or refresh == 'true'
      current_user.friend_statuses(friend_id)
      @profile = User.friend_profile_including_those_with_no_statuses(id,friend_id)
    end
    @type = "user_image_#{friend_id}"
    @number = params[:number]
    @max = params[:max]
    render :layout=>false, :partial => 'load'
  end
  
  def index
  end
  
  def refresh
    current_user.refresh
    redirect_to :action => 'slow_cloud'
  end
  
  def cloud
    # could authenticate depending on presence or absence of id ...
    # maybe save that till after BDD??? actually it's real complicated to leave it ...
    id = params[:id] || current_user.twitter_id
    @user = User.find_by_twitter_id(id) || current_user
    @friends = @user.friends
    @refresh = params[:refresh]
  end
  
  #Retreive the friend timeline
  def tweets
    @tweets = current_user.twitter.get('/statuses/friends_timeline')
    logger.info @tweets
  end

end
